#include "SharedTest.h"
#include <chrono>
using namespace zanxin;

SharedTest::SharedTest()
{
    shmId_ = shmget((key_t)Shm_addrees, sizeof(SharedData), 0666|IPC_CREAT);
    pShareData_ = static_cast<SharedData*>(shmat(shmId_, nullptr, 0));
    semId_ = semget(shmId_, 1, 0666 | IPC_CREAT);
    semctl(semId_, 0, SETVAL, 1);
    cout<<"共享内存地址 ： "<< (int *)(pShareData_)<<endl;
}

SharedTest::~SharedTest()
{
    semctl(semId_, 0, IPC_RMID);
    shmdt(static_cast<const void*>(pShareData_));
    shmctl(shmId_, IPC_RMID, nullptr);
    cout<<"共享内存已经销毁"<<endl;
}

SharedData SharedTest::GetData()
{
    SharedData ret;
    this->Lock();
    memcpy(&ret, this->pShareData_, sizeof (SharedData));
    this->Unlock();
    return ret;
}

int SharedTest::SetData(const SharedData &data)
{
//    static auto timer = std::chrono::high_resolution_clock::now();
    this->Lock();
    memcpy(this->pShareData_, &data, sizeof (SharedData));
    this->Unlock();
//    cout<<"cycle time="<<std::chrono::duration_cast<std::chrono::microseconds>(
//              std::chrono::high_resolution_clock::now() - timer).count()<<endl;
//    timer = std::chrono::high_resolution_clock::now();
    return 0;
}

void SharedTest::Lock()
{
    struct sembuf sem;
    sem.sem_flg = 0;
    sem.sem_num = 0;
    sem.sem_op = -1;
    semop(semId_, &sem, 1);
}

void SharedTest::Unlock()
{
    struct sembuf sem;
    sem.sem_flg = 0;
    sem.sem_num = 0;
    sem.sem_op = 1;
    semop(semId_, &sem, 1);
}

extern "C" {

zanxin::SharedTest useShare;
zanxin::SharedData getdata(){
    return useShare.GetData();
}
int setdata(zanxin::SharedData data){
    return useShare.SetData(data);
}

}
